//
//  PersonalVC.m
//  sensen_ios
//
//  Created by pro on 16/1/30.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "PersonalVC.h"

//控制器
#import "LoginVC.h"

//二层界面
#import "PersonalSettingVC.h"
#import "OrderTotalVC.h"
#import "SalesAfterListVC.h"
#import "ManageAddressVC.h"
#import "CollectionVC.h"
#import "PostVC.h"
#import "WebVC.h"
#import "IntegralMallVC.h"
#import "WebViewController.h"
#import "WebIntegralViewController.h"//积分商城
#import "DailyCheckWebVC.h"//每日签到单独处理
//单元格
#import "PersonCenterCell.h"


//待付款，待发货等
#import "TitleImageControlView.h"


@interface PersonalVC ()<UITableViewDataSource, UITableViewDelegate>{
     UIView              * _header_View;             // 顶部视图  登陆等
}

@property (nonatomic, strong) UITableView *tableView; // 表视图
@property (nonatomic, strong) UIImageView *headerView; // 头像
@property (nonatomic, strong) UILabel *nameView; // 用户名

@property (nonatomic, strong) NSArray *cellImgAry; // 单元格图片数组
@property (nonatomic, strong) NSArray *cellTitleAry; // 单元格标题数组
@property (nonatomic, strong) NSArray *cellintroAry; // 单元格介绍数组


@end

@implementation PersonalVC


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    //[self _initNavi];
    [self.navigationController setNavigationBarHidden:YES animated:YES];

    // 设置头像
    UserModel *user = [CommonCache getUserInfo];
    if (user != nil) {
        [self.headerView setImageWithURL:[NSURL URLWithString:user.head] placeholderImage:[UIImage imageNamed:@"默认头像.jpg"]];
    } else {
        self.headerView.image = [UIImage imageNamed:@"默认头像.jpg"];
    }
    
    if (user != nil){
            // 如果是微信登录，则显示昵称 ,
            if (![user.reg_from isEqualToString:@"2"] ) {
                if (user.nickname.length > 0) {
                    _nameView.text = user.nickname;
                    
                }else{
                    NSMutableString *name = [NSMutableString stringWithString:user.username];
                    [name replaceCharactersInRange:NSMakeRange(4, 5) withString:@"****"];
                    _nameView.text = name;
                }
            }
            else {
                _nameView.text = user.nickname;
                
            }
        
    }else{
        _nameView.text = @"Hi，你好";
    }

    
    
    
}

#pragma mark - 设置导航栏属性
- (void)_initNavi {
    
    [self isNaviTranslucent:NO statesLightContent:YES];
    
    // 设置标题的颜色
    NSDictionary *attr = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
    [self.navigationController.navigationBar setTitleTextAttributes:attr];
    
}



- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];
    
    [self _initData];
    [self _initViews];
    
}
#pragma mark -- 初始化数据 --
- (void)_initData {
    
    // 第三组数据化单元格显示的数据数组
    // 1.单元格标题数组
    _cellTitleAry = @[@"我的资产",
                      @"收货地址管理",
                      @"我的收藏",
                      @"我的帖子",
                      @"更多设置"
                     ];
    // 2.单元格图片数组
    _cellImgAry = @[@"个人中心_我的资产",
                    @"个人中心_收货地址管理",
                    @"个人中心_我的收藏",
                    @"我的帖子_07",
                    @"个人中心_更多设置"
                    ];
    // 3.单元格介绍数组
    _cellintroAry = @[@"查看我的资产",
                      @"管理收货地址",
                      @"查看收藏夹",
                      @"查看我的帖子",
                      @"查看更多设置"
                      ];

    
}

#pragma mark -- 创建视图 --
- (void)_initViews {
    
    
    [self buildHeaderView];
    [self _initTableView]; // 创建表视图
}
// 创建表视图
- (void)_initTableView {
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 49) style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.tableHeaderView = _header_View;

    [self.view addSubview:_tableView];
    
    
    UILabel * lable  = [[UILabel alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - 100) / 2, 20, 100, 30)];
    lable.text = @"个人中心";
    lable.textColor = [UIColor whiteColor];
    lable.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:lable];
   
    lable.hidden = YES;
   
}

//  创建顶部视图
-(void)buildHeaderView{
    //背景551/2
    _header_View = [[UIView alloc] init];
    _header_View.frame = CGRectMake(0, 0, SCREEN_WIDTH, 250);
    _header_View.backgroundColor = [UIColor clearColor];
    
    // 个人中心背景图片
    UIImageView *bgImgView = [[UIImageView alloc] initWithFrame:_header_View.bounds];
    bgImgView.image = [UIImage imageNamed:@"个人中心_01"];
    bgImgView.contentMode = UIViewContentModeScaleToFill;
    bgImgView.tag = 666;
    [_header_View addSubview:bgImgView];
    
    
    // 创建头像
    CGFloat width = SCREEN_WIDTH / 4;
    CGFloat height = SCREEN_WIDTH / 4;
    CGFloat x = (_header_View.width - width) / 2.0;
    
    _headerView = [[UIImageView alloc] initWithFrame:CGRectMake(x,_header_View.height - 180, width, height)];
    _headerView.backgroundColor = [UIColor lightGrayColor];
    _headerView.image = [UIImage imageWithColor:[UIColor whiteColor]];
    _headerView.layer.cornerRadius = _headerView.width / 2;
    _headerView.layer.masksToBounds = YES;
    // 设置头像
    UserModel *user = [CommonCache getUserInfo];
    if (user != nil && ![user.head isStringNull]) {
        [self.headerView setImageWithURL:[NSURL URLWithString:user.head] placeholderImage:[UIImage imageNamed:@"默认头像"]];
    }
    [_header_View addSubview:_headerView];
    _headerView.userInteractionEnabled = YES;
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [_headerView addGestureRecognizer:tap];
    
    //创建用户名
    _nameView = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 3, _headerView.bottom + 8, SCREEN_WIDTH / 3, SCREEN_WIDTH / 10)];
    _nameView.textAlignment = NSTextAlignmentCenter;
    _nameView.text = [BoyeTool getEncryptMobile:_nameView.text];
    _nameView.textColor = [UIColor whiteColor];
    if (user != nil) {
        if (user.nickname.length == 0) {
            _nameView.text = @"初来乍到";
        }else{
        _nameView.text = user.nickname;
        }
    }else{
        _nameView.text = @"Hi，你好";
    }
    _nameView.userInteractionEnabled = YES;
    UITapGestureRecognizer * tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [_nameView addGestureRecognizer:tap1];
    [_header_View addSubview:_nameView];

    
}
- (void)tapAction:(UITapGestureRecognizer *)tap{
     UserModel *user = [CommonCache getUserInfo];
    if (user.uid == nil) {
        LoginVC *vc = [[LoginVC alloc] init];
        BaseNavVC *naviVC = [[BaseNavVC alloc] initWithRootViewController:vc];
        [self presentViewController:naviVC animated:YES completion:nil];
    }else{
        PersonalSettingVC *vc = [[PersonalSettingVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}


#pragma mark - UITableViewDataSource UITableViewDelegate
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 1;
            break;
        case 1:
            return 2;
            break;
        case 2:
            return 5;
            break;
        default:
            return 0;
            break;
    }
}

// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PersonCenterCell *cell= [PersonCenterCell cellWithTableView:tableView];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    /* 忽略点击效果 */
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    //第一区
    if (indexPath.section == 0) {
        static NSString * cellIdentifier = @"PersonCell";
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell ==nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            NSArray *imgNames = @[@"个人中心_每日签到",
                                  @"个人中心_积分商城",
                                  @"个人中心_邀请有奖"
                                  ];
            NSArray *titles = @[@"每日签到",
                                @"积分商城",
                                @"邀请有奖"
                                ];
            
            CGFloat width = SCREEN_WIDTH / 3;
            CGFloat height = 60;
            
            
            for (int i = 0; i < titles.count; i ++) {
                
                UIView *sectionView = [[UIView alloc] initWithFrame:CGRectMake(width * i, 0, width, height)];
                sectionView.tag = 200 + i;
                [cell addSubview:sectionView];
                // 添加手势
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sectionViewTap:)];
                [sectionView addGestureRecognizer:tap];
                
                UIImageView *imgView = [[UIImageView alloc] init];
                imgView.image = [UIImage imageNamed:imgNames[i]];
                [sectionView addSubview:imgView];
                [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(sectionView).offset(10);
                    make.centerX.equalTo(sectionView.mas_centerX);
                    make.size.mas_equalTo(CGSizeMake(height * 0.4, height * 0.4));

                }];
                imgView.userInteractionEnabled = YES;
                
                UILabel *titleLabel = [[UILabel alloc] init];
                titleLabel.userInteractionEnabled = YES;
                titleLabel.font = FONT(12);
                titleLabel.text = titles[i];
                titleLabel.textColor = [UIColor darkGrayColor];
                titleLabel.textAlignment = NSTextAlignmentCenter;
                [sectionView addSubview:titleLabel];
                [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerX.equalTo(sectionView.mas_centerX);
                    make.size.mas_equalTo(CGSizeMake(height * 1.5, 13));
                    make.bottom.equalTo(sectionView.mas_bottom).offset(-10);
                }];
               
                
            }

        }
        /* 忽略点击效果 */
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        
        return cell;
    //第二区
    }else if(indexPath.section == 1){
        if (indexPath.row == 0) {
            cell.titleLabel.text = @"全部订单";
            cell.introduceLabel.text = @"查看全部订单";
            cell.introduceLabel.textColor = [UIColor darkGrayColor];
            cell.headImgView.image = [UIImage imageNamed:@"个人中心_全部订单"];
            return cell;
        }else{
            
            static NSString * cellIdentifier = @"PersonOrderCell";
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell ==nil) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
                //订单图片数组
                NSArray * orderImageArray = @[@"个人中心_代付款",
                                              @"个人中心_待发货",
                                              @"个人中心_待收货",
                                              @"个人中心_退款售后"
                                              ];
                
                //订单标题数组
                NSArray * orderTitleArray = @[@"待付款",
                                              @"待发货",
                                              @"待收货",
                                              @"退款售后"
                                              ];
                //对应订单个数数组
                NSArray * orderCountArray = @[@1,
                                              @2,
                                              @3,
                                              @4
                                              ];
                for (int i = 0; i < 4; i++) {
                    NSNumber * number = orderCountArray[i];
                    NSInteger count = [number integerValue];
                    CGFloat width = SCREEN_WIDTH / 4;
                    CGFloat height = 64;
                    TitleImageControlView * view = [[TitleImageControlView alloc] initWithFrame:CGRectMake(width * i, 0, width, height) Image:orderImageArray[i] Title:orderTitleArray[i] count:(int)count];
                    [cell addSubview:view];
                    view.tag = 100 + i;
                    [view addTarget:self action:@selector(viewAction:)  forControlEvents:UIControlEventTouchUpInside];
                }

            }
            
    
            return cell;
        }
    //第三区
    }else{
        cell.titleLabel.text = _cellTitleAry[indexPath.row];
        cell.introduceLabel.text = _cellintroAry[indexPath.row];
        cell.headImgView.image = [UIImage imageNamed:_cellImgAry[indexPath.row]];
        /* 忽略点击效果 */
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }
       


}


// 设置单元格高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 60;
    }else if (indexPath.section == 1 && indexPath.row == 1){
        return 60;
    }else{
        return 44;
    }
    
}
// 设置组头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 5;

}


- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    return view;
}


// 设置组尾高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];// 取消选中阴影
    
     UserModel *user = [CommonCache getUserInfo];
    if (!user.uid) {
        LoginVC *vc = [[LoginVC alloc] init];
        BaseNavVC *naviVC = [[BaseNavVC alloc] initWithRootViewController:vc];
        [self presentViewController:naviVC animated:YES completion:nil];
        return;
    }

    if (indexPath.section == 2) {
        if (indexPath.row == 4) {
            PersonalSettingVC * VC = [[PersonalSettingVC alloc] init];
            [self.navigationController pushViewController:VC animated:YES];
        }
        
        else if (indexPath.row == 1){
            ManageAddressVC *vc = [[ManageAddressVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        
        
        else if (indexPath.row == 2){
            CollectionVC *vc = [[CollectionVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        
        else if (indexPath.row == 3){
            PostVC *vc = [[PostVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        
        
        else if (indexPath.row == 0){
            WebVC *vc = [[WebVC alloc] initWithUrlString:[NSString stringWithFormat:@"Index/assert?uid=%@&psw=%@", user.uid, user.password]];
            vc.titleString = @"我的资产";
            [self.navigationController pushViewController:vc animated:YES];

            
       }
        
    }
    
    else if (indexPath.section == 1 && indexPath.row == 0) {
        OrderTotalVC *vc =[[OrderTotalVC alloc] init];
        vc.intFirstSelect = 0;
        [self.navigationController pushViewController:vc animated:YES];
        
        
    }
}


// 表视图滑动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat offSetY = scrollView.contentOffset.y;// 偏移量（负）
    CGFloat scale = (- offSetY) / (551/2.0) + 1;
    if (offSetY < 0) {
        UIImageView *bgImageView = (UIImageView *)[_header_View viewWithTag:666];
        bgImageView.transform = CGAffineTransformMakeScale(scale, scale);
        bgImageView.center = CGPointMake(_header_View.center.x, 0);
        bgImageView.top = offSetY;
        
    }
}



#pragma mark - 点击事件
- (void)rightAction:(UIButton *)button {
    LoginVC *vc = [[LoginVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark 待付款按钮跳转
- (void)viewAction:(UIControl *)sender{
    
    UserModel *user = [CommonCache getUserInfo];
    if (!user.uid) {
        LoginVC *vc = [[LoginVC alloc] init];
        BaseNavVC *naviVC = [[BaseNavVC alloc] initWithRootViewController:vc];
        [self presentViewController:naviVC animated:YES completion:nil];
        return;
    }

    if (sender.tag == 103) {
        SalesAfterListVC * vc = [[SalesAfterListVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
    }else{
        OrderTotalVC  * vc = [[OrderTotalVC alloc] init];
        vc.intFirstSelect = sender.tag - 99;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)sectionViewTap:(UITapGestureRecognizer *)tap {

    UserModel *user = [CommonCache getUserInfo];
    if (!user.uid) {
        LoginVC *vc = [[LoginVC alloc] init];
        BaseNavVC *naviVC = [[BaseNavVC alloc] initWithRootViewController:vc];
        [self presentViewController:naviVC animated:YES completion:nil];
        return;
    }
    NSLog(@"%@", user.uid);
    NSLog(@"%@", user.password);
    //每日签到
    if (tap.view.tag == 200) {
        DailyCheckWebVC *vc = [[DailyCheckWebVC alloc] initWithUrlString:[NSString stringWithFormat:@"Index/signIn?uid=%@&psw=%@", user.uid, user.password]];
        vc.titleString = @"每日签到";
        [self.navigationController pushViewController:vc animated:YES];
      
        
    }
    //积分商城
    else if (tap.view.tag == 201){
        
//        IntegralMallVC *vc = [[IntegralMallVC alloc] init];
//        [self.navigationController pushViewController:vc animated:YES];
        
        WebVC *vc = [[WebVC alloc] initWithUrlString:[NSString stringWithFormat:@"ScoreGoods/index?uid=%@&psw=%@", user.uid, user.password]];
        vc.titleString = @"积分商城";
        [self.navigationController pushViewController:vc animated:YES];


    }
    //邀请有奖
    else if (tap.view.tag == 202){
        
//        WebViewController *vc = [[WebViewController alloc] initWithUrlString:[NSString stringWithFormat:@"%@/Index/invitationAward?uid=%@&psw=%@",WEB_BASE_URL, user.uid, user.password]];
//        vc.titleString = @"邀请有奖";
//        [vc createRightBarButtonItemWithImagename:@"论坛首页_详情页_分享"];
//        [self.navigationController pushViewController:vc animated:YES];
        
        
                WebIntegralViewController *vc = [[WebIntegralViewController alloc] initWithUrlString:[NSString stringWithFormat:@"%@/Index/invitationAward?uid=%@&psw=%@",WEB_BASE_URL, user.uid, user.password]];
                vc.titleString = @"邀请有奖";
                //[vc createRightBarButtonItemWithImagename:@"论坛首页_详情页_分享"];
                [self.navigationController pushViewController:vc animated:YES];
    
        
    }
    
}

#pragma mark 分割线距离左边距离
-(void)viewDidLayoutSubviews
{
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}





@end
